﻿using SIMS.Shared.Models;
using SIMS.SqlSugarWebApi.Models;
using SIMS.SqlSugarWebApi.ServiceInterface;
using SqlSugar;

namespace SIMS.SqlSugarWebApi.Services
{
    public class CourseService : BaseService<Course>, ICourseService
    {
        private DataContext _context;

        public CourseService(DataContext context) : base(context)
        {
            _context = context;
        }
    
        public async Task<PagingModel<Course>> GetCourses(string courseName, string teacher, int pageNum, int pageSize)
        {
            ISugarQueryable<Course> courses;
            if (!string.IsNullOrEmpty(courseName) && !string.IsNullOrEmpty(teacher))
            {
                courses = _context.db.Queryable<Course>().Where(r => r.Name.Contains(courseName) && r.Teacher.Contains(teacher)).OrderBy(r => r.Id);
            }
            else if (!string.IsNullOrEmpty(courseName))
            {
                courses = _context.db.Queryable<Course>().Where(r => r.Name.Contains(courseName)).OrderBy(r => r.Id);
            }
            else if (!string.IsNullOrEmpty(teacher))
            {
                courses = _context.db.Queryable<Course>().Where(r => r.Teacher.Contains(teacher)).OrderBy(r => r.Id);
            }
            else
            {
                courses = _context.db.Queryable<Course>().OrderBy(r => r.Id);
            }

            int count = await courses.CountAsync();
            List<Course> items;
            if (pageSize > 0)
            {
                items = await courses.ToPageListAsync(pageNum, pageSize);
            }
            else
            {
                items = await courses.ToListAsync();
            }
            return new PagingModel<Course>()
            {
                Count = count,
                Items = items
            };
        }
    }
}
